﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UserRepository.cs" company="">
//   Copyright (c) 2010/2011 All Right Reserved
// </copyright>
// <summary>
//   Contains UserRepository class declaration.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace iBuproModel.Repositories.Classes
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using iBuproModel;
    using iBuproModel.Repositories.Interfaces;

    /// <summary>
    /// Implements IUserRepository interface using linq to entities.
    /// </summary>
    public class UserRepository : GenericRepository<User>, IUserRepository
    {
        public User GetUserByUserName(string username)
        {
            var user = context.Users.FirstOrDefault(u => u.Username == username);
            return user ?? null;
        }

        public bool IsUserInRole(User user, string rolename)
        {
            IRoleRepository roles = repositoryService.RoleRepositoryCreateInstance();
            Role role = roles.First(r => r.Name == rolename);
            User pomUser = this.First(u => u.Id == user.Id);
            if (pomUser == null)
                throw new Exception("Cannot find user");
            if (role == null)
                throw new Exception("Cannot find role");

            return pomUser.Roles.Contains(role);
        }


        public IEnumerable<Role> GetRolesForUser(User user)
        {
            return context.Users.Where(u => u.Id == user.Id).FirstOrDefault().Roles;
        }

        public new IQueryable<User> GetAll()
        {
            return this.context.Users.OrderBy(user => user.FirstName).ThenBy(user => user.LastName).ThenBy(user => user.Username);
        }

        public void UpdateRoleList(User user, IEnumerable<int> ids)
        {
            user.Roles.Clear();

            foreach (var id in ids)
            {
                user.Roles.Add(context.Roles.First(r => r.Id == id));
            }
            IUserRepository users = repositoryService.UserRepositoryCreateInstance();
            users.SaveChanges();
        }
    }
}
